package demo506;

import java.io.*;

public class Text02 {
    public static void main(String[] args) {
        String filePath = "example.txt";

        try(BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))){
            writer.write("你好这是第一行文本 \n");
            writer.write("这是第二行内容 \n");
            writer.append("使用append方法添加的第三行");
            System.out.println(("文件写入成功"));
        } catch (IOException e) {
            System.err.println("写入文件时发生错误:" + e.getMessage());
            throw new RuntimeException(e);
        }

        System.out.println("\n开始读取文件内容:");
        try(BufferedReader reader = new BufferedReader(new FileReader(filePath))){
            String line;
            int lineNumber = 1;
            while((line = reader.readLine()) != null){
                System.out.println("第" + lineNumber + "行" + line);
                lineNumber++;
            }
        } catch (FileNotFoundException e) {
            System.err.println("读取文件时发生错误：" + e.getMessage());
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

